package com.example.dhhyc.demos.web;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.encoder.Encoder;
import ch.qos.logback.core.rolling.RollingFileAppender;
import java.io.IOException;

/**
 * TODO
 *
 * @author jijianchao
 * @date 2023/7/11 19:01
 */
public class MonitorAppender extends RollingFileAppender<ILoggingEvent> {




    @Override
    public void setEncoder(Encoder encoder) {
        //自定义的appender的父类OutputStreamAppender在启动的时候会判断是否有encoder ，无的话自定义appender启动会失败
        super.setEncoder(encoder);
    }
    /**
     * 覆盖父类OutputStreamAppender的日志记录功能，再这里面做日志切操作功能
     *
     * @param event
     */
    protected void subAppend(ILoggingEvent event) {
        if (this.isStarted()) {
            monitor(event);
        }
        super.subAppend(event);

    }

    private void monitor(ILoggingEvent event) {
        if (event.getLevel().equals(Level.ERROR)) {
            System.out.println("发生错误后的需要做的事");

            String errorMessage = new String(encoder.encode(event));


            String className = "";
            String method = "";
            String line = "";

            StackTraceElement[] stackTraceElements = event.getCallerData();
            if (stackTraceElements.length > 0) {
                StackTraceElement stackTraceElement = stackTraceElements[0];
                className = stackTraceElement.getClassName();
                method = stackTraceElement.getMethodName();
                line = String.valueOf(stackTraceElement.getLineNumber());

            } else {
                className=event.getThreadName();
            }


            System.out.println("20240417!@#$%^&*()_"+errorMessage+"/"+className);
        }
//        System.out.println("logback-custom你好");

    }




    /**
     * 飞书报警
     *
     * @param byteArray
     * @methodName: sendFs
     * @return: void
     * @author: ybw
     * @date: 2022/9/15
     **/
    private void sendFs(byte[] byteArray) {
        if (byteArray != null && byteArray.length != 0) {
            this.lock.lock();
            try {

            } finally {
                this.lock.unlock();
            }
        }
    }

    private void writeBytes(byte[] byteArray) throws IOException {
        if (byteArray != null && byteArray.length != 0) {
            this.lock.lock();
            try {
                this.getOutputStream().write(byteArray);
                if (this.isImmediateFlush()) {
                    this.getOutputStream().flush();
                }
            } finally {
                this.lock.unlock();
            }
        }
    }


}
